package com.ping.demo;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.ping.common.Json;
import com.ping.interceptor.DemoInterceptor;
import com.ping.model.Brand;

public class JFinalDemoController extends Controller{
	public void index(){
		renderText("Hello JFinal World");
	}
	
	public void tmpdir(){
		String path = System.getProperty("java.io.tmpdir");
		renderText(path);
	}
	
	public void post(){
		System.out.println(getPara());
		renderText(getPara(""));
	}
	
	public void get(){
		renderText(getPara());
	}
	
/*	public void initial(){
		Brand brand = new Brand();
		brand.initial(20);
		renderText("success");
	}*/
	
	public void cats(){
		List<Record> cats = Brand.findCats();
		System.out.println(cats.get(0));
		renderText("success");
	}
	
	@Before(DemoInterceptor.class)
	public void hot(){
		List<Record> hots = Brand.findHotBrands();
		
		JSONObject result = new JSONObject();
		JSONArray array = null;
		try {
			array = Json.ListToJsonArray(hots);
			result.put("hots", array);
		} catch (JSONException e) {
			// TODO: handle exception
			System.out.println("Json Opreation has error!");
		}
		String jsons = result.toString();
		renderText("success\n"+jsons);
	}
	
	public void brand() throws JSONException{
		String cat = getPara("cat");
		List<Record> brands = Brand.findBrandsByCat(cat);
		JSONArray array = Json.ListToJsonArray(brands);
		JSONObject result = new JSONObject();
		result.put("brands", array);
		
		renderText(result.toString());
	}
}
